#!/usr/bin python3
# -*- coding: utf-8 -*-
"""任务处理services"""
import uuid

from gtm_server.common.common import create_http_request
from gtm_server.common.task import BaiDuWebServerUrl
from gtm_server.common.constant import TaskStatusKeys
from gtm_server.common.database_pg import DBPool
from gtm_server.common.common import get_current_time

from gtm_server.dao.tasks import insert_task_in_table_dao
from gtm_server.dao.tasks import insert_step_in_table_dao
from gtm_server.dao.tasks import get_all_task


def create_task_smart(type="drive", ori_lat="40.01116", ori_lng="116.339303",
                      de_lat="39.936404", de_lng="116.452562"):
    """
    根据路线规划类型生成路线，默认驾驶类型
    """
    url = BaiDuWebServerUrl(ori_lat, ori_lng, de_lat, de_lng)
    api = url.create_way_api(type=type)
    way = create_http_request(url=api, type="GET")

    return way


def create_task_diy(info):
    """
    根据自定义路线数据规划路线
    """

    return


def analysis_way_data(way, name="测试路线(默认)", brief="测试路线介绍"):
    """
    解析百度路线规划返回的结果，输出task_info和step_info
    1. task_info:{
            id: uuid,
            name: "",
            ori_lat: 45.567,
            ori_lng: 116.354,
            de_lat: 46.123,
            de_lng: 118.125,
            create_time: ,
            brief: "",
            pre_duration: 11568.5(s)
            index: 4,
            steps: 2,
            distance: 54855
    }
    """
    if way.get("status") != 0:
        return TaskStatusKeys.FAILED
    else:
        task_info = {}
        id = uuid.uuid4()
        create_time = get_current_time()

        # 临时数据
        index = 2

        # 提取具体内容信息，TODO:当前只提取路线的第一条
        data = way.get("result").get("routes")[0]

        task_info["id"] = id
        task_info["name"] = name
        task_info["ori_lat"] = data.get("origin").get("lat")
        task_info["ori_lng"] = data.get("origin").get("lng")
        task_info["de_lat"] = data.get("destination").get("lat")
        task_info["de_lng"] = data.get("destination").get("lng")
        task_info["create_time"] = create_time
        task_info["brief"] = brief
        task_info["pre_duration"] = data.get("duration")
        task_info["index"] = index
        task_info["distance"] = data.get("distance")

        steps_info = analysis_steps_data(data=data, task_id=task_info.get("id"))

        task_info["steps"] = len(steps_info)

        return task_info, steps_info


def analysis_steps_data(data, task_id):
    """
    解析路线信息的分步数据
    搭配 analysis_way_data() 函数使用
    1. step_info:{
            id: uuid,
            task_id: uuid,
            leg_index: 4,
            direction: 5,
            distance: 5896,
            road_name: 明德路，
            road_type: 其他路，
            start_lat: 45.567,
            start_lng: 116.354,
            end_lat: 46.123,
            end_lng: 118.125,
            path: ""
    }
    """
    if data.get("steps") is None:
        return TaskStatusKeys.FAILED
    else:
        steps_info = []
        no = 0

        # 提取steps的详细信息
        steps = data.get("steps")

        for step in steps:
            step_info = {}

            step_info["id"] = uuid.uuid4()
            step_info["task_id"] = task_id
            step_info["leg_index"] = step.get("leg_index")
            step_info["direction"] = step.get("direction")
            step_info["distance"] = step.get("distance")
            step_info["road_name"] = step.get("road_name")
            step_info["road_type"] = step.get("road_type")
            step_info["start_lat"] = step.get("start_location").get("lat")
            step_info["start_lng"] = step.get("start_location").get("lng")
            step_info["end_lat"] = step.get("end_location").get("lat")
            step_info["end_lng"] = step.get("end_location").get("lng")
            step_info["path"] = step.get("path")
            no += 1
            step_info["no"] = no
            steps_info.append(step_info)

        return steps_info


def insert_task_in_table(task_info, steps_info):
    """
    Args: task (统一方法create_way的返回结果)
        {

        }
    插入一条生成的任务信息到数据库中
    """

    with DBPool().get_session() as session:
        result1 = insert_task_in_table_dao(session=session, task_info=task_info)

        for step_info in steps_info:
            result2 = insert_step_in_table_dao(session=session, step_info=step_info)

    if result1 is TaskStatusKeys.SUCCESS and result2 is TaskStatusKeys.SUCCESS:
        return TaskStatusKeys.SUCCESS
    else:
        return TaskStatusKeys.FAILED


def get_all_task_major_info():
    """
    获取所有任务的主要信息列表(不包括step_info)
    """
    with DBPool().get_session() as session:
        tasks_info = get_all_task(session=session)
        tasks = format_task_major_info(tasks_info=tasks_info)

    return tasks


def format_task_major_info(tasks_info):
    """
    Args:
        Model Object
    return:
        tasks: []

    格式化task的主要信息 （不包括step_info）
    """
    tasks = []

    for task in tasks_info:
        task_info = {}
        task_info["id"] = task.id
        task_info["name"] = task.name
        task_info["ori_lat"] = task.ori_lat
        task_info["ori_lng"] = task.ori_lng
        # 根据经纬度获取地理名
        address = get_address_by_points(lat=task.ori_lat, lng=task.ori_lng)
        task_info["address"] = address
        task_info["brief"] = task.brief
        # 转换datetime格式为字符串
        create_time = str(task.create_time)
        task_info["create_time"] = create_time

        tasks.append(task_info)

    return tasks


def get_address_by_points(lat, lng):
    """
    根据经纬度点位获取地址信息
    调用百度逆地址编码服务api
    """
    url = BaiDuWebServerUrl(ori_latitude=lat, ori_longitude=lng)
    api = url.transform_points_api()

    result = create_http_request(url=api, type="GET")

    if result.get("status") != 0:
        return TaskStatusKeys.FAILED
    else:
        address = result.get("result").get("formatted_address", "")
        return address


def get_points_by_address(address):
    """
    根据地址信息获取经纬度
    调用百度地址编码服务api
    """
    url = BaiDuWebServerUrl()
    api = url.transform_address_api(address=address)

    result = create_http_request(url=api, type="GET")

    if result.get("status") != 0:
        return TaskStatusKeys.FAILED
    else:
        point = result.get("result").get("location", "")
        return point


def format_task_info_of_senior_method(data):
    """
    解析打包高级模式创建的路线规划的参数
    return task_info steps_info
    """
    task_info = {}
    create_time = get_current_time()
    id = uuid.uuid4()

    task_info["id"] = id
    task_info["name"] = data.get("task_name")
    task_info["brief"] = data.get("task_brief")
    task_info["ori_lat"] = None
    task_info["ori_lng"] = None
    task_info["de_lat"] = None
    task_info["de_lng"] = None
    task_info["pre_time"] = data.get("pre_time")
    task_info["create_time"] = create_time
    task_info["pre_duration"] = data.get("duration")
    task_info["index"] = None
    task_info["distance"] = None

    steps_data = data.get("way_data")
    steps_info = format_steps_info_of_senior_method(task_id=id, steps_data=steps_data)
    return task_info, steps_info


def format_steps_info_of_senior_method(task_id, steps_data):
    """
    解析打包高级模式创建的路线规划的steps参数
    """
    steps_info = []
    no = 0

    for step in steps_data:
        step_info = {}

        step_info["id"] = uuid.uuid4()
        step_info["task_id"] = task_id
        step_info["leg_index"] = None
        step_info["direction"] = None
        step_info["distance"] = None
        step_info["road_name"] = None
        step_info["road_type"] = None
        step_info["start_lat"] = step.get("lat")
        step_info["start_lng"] = step.get("lng")
        step_info["end_lat"] = None
        step_info["end_lng"] = None
        step_info["path"] = None
        no += 1
        step_info["no"] = no
        steps_info.append(step_info)

    return steps_info


def create_task(data):
    """
    创建任务的总调度入口，根据传入的task信息，选择创建方法
    1. 调用百度api智能生成
    2. 根据传入的路线详情创建任务
    """
    if data.get("way_data") == []:
        # 提取信息
        name = data.get("task_name")
        brief = data.get("task_brief")
        if data.get("ori_lat") != "":
            ori_lat = data.get("ori_lat")
            ori_lng = data.get("ori_lng")
            de_lat = data.get("de_lat")
            de_lng = data.get("de_lng")
        elif data.get("ori_position") != "":
            ori_point = get_points_by_address(address=data.get("ori_position"))
            de_point = get_points_by_address(address=data.get("de_position"))
            ori_lat = ori_point.get("lat")
            ori_lng = ori_point.get("lng")
            de_lat = de_point.get("lat")
            de_lng = de_point.get("lng")
        else:
            return -1
        # 选择智能规划方法
        way = create_task_smart(ori_lat=ori_lat, ori_lng=ori_lng,
                      de_lat=de_lat, de_lng=de_lng)
        task_info, steps_info = analysis_way_data(way=way, name=name, brief=brief)
        print(f"task_info{task_info}")
        status = insert_task_in_table(task_info=task_info,
                                      steps_info=steps_info)
        print(f"status:{status}")
        if status == TaskStatusKeys.SUCCESS:
            return 0
        else:
            return -1

    else:
        # 选择自定义路线规划
        task_info, steps_info = format_task_info_of_senior_method(data=data)
        print(f"task_info{task_info}, steps_info{steps_info}")
        status = insert_task_in_table(task_info=task_info,
                                      steps_info=steps_info)
        print(f"status:{status}")
        if status == TaskStatusKeys.SUCCESS:
            return 0
        else:
            return -1



if __name__ == "__main__":
    # 功能单独测试
    way = create_task_smart()
    task_info, steps_info = analysis_way_data(way)

    insert_task_in_table(task_info=task_info, steps_info=steps_info)
    print(f"task_info{task_info}")
    get_address_by_points("40.000022","116.33936")
    get_points_by_address(address="北京市海淀区清华东路")
    tasks = get_all_task_major_info()
    print(f"tasks:{tasks}")